import { Plugin } from "siyuan"
import { createApp } from 'vue'
import App from './App.vue'

// Element Plus 按需引入
import {
  ElHeader,
  ElMain,
  ElFooter,
  ElIcon,
  ElTag,
  ElButton,
  ElButtonGroup,
  ElTooltip,
  ElAvatar,
  ElInput,
  ElForm,
  ElFormItem,
  ElCheckbox,
  ElSelect,
  ElOption,
  ElMessage,
  ElNotification,
  ElMessageBox
} from 'element-plus'
import 'element-plus/es/components/header/style/css'
import 'element-plus/es/components/main/style/css'
import 'element-plus/es/components/footer/style/css'
import 'element-plus/es/components/icon/style/css'
import 'element-plus/es/components/tag/style/css'
import 'element-plus/es/components/button/style/css'
import 'element-plus/es/components/button-group/style/css'
import 'element-plus/es/components/tooltip/style/css'
import 'element-plus/es/components/avatar/style/css'
import 'element-plus/es/components/input/style/css'
import 'element-plus/es/components/form/style/css'
import 'element-plus/es/components/form-item/style/css'
import 'element-plus/es/components/checkbox/style/css'
import 'element-plus/es/components/select/style/css'
import 'element-plus/es/components/option/style/css'
import 'element-plus/es/components/message/style/css'
import 'element-plus/es/components/notification/style/css'
import 'element-plus/es/components/message-box/style/css'

let plugin: Plugin | null = null
let app: any = null

export function usePlugin(pluginProps?: Plugin): Plugin {
  if (pluginProps) plugin = pluginProps
  if (!plugin) {
    console.error('需要绑定插件实例，请在插件的main.ts中调用usePlugin(plugin) 绑定插件实例')
  }
  return plugin!
}

export function init(plugin: Plugin) {
  usePlugin(plugin)

  const div = document.createElement('div')
  div.classList.toggle('my-plugin-app')
  div.id = this.name
  
  app = createApp(App)
  
  // 注册 Element Plus 组件
  app.use(ElHeader)
  app.use(ElMain)
  app.use(ElFooter)
  app.use(ElIcon)
  app.use(ElTag)
  app.use(ElButton)
  app.use(ElButtonGroup)
  app.use(ElTooltip)
  app.use(ElAvatar)
  app.use(ElInput)
  app.use(ElForm)
  app.use(ElFormItem)
  app.use(ElCheckbox)
  app.use(ElSelect)
  app.use(ElOption)
  
  // 全局配置消息组件
  app.config.globalProperties.$message = ElMessage
  app.config.globalProperties.$notify = ElNotification
  app.config.globalProperties.$msgbox = ElMessageBox
  app.config.globalProperties.$messageBox = ElMessageBox
  app.config.globalProperties.$confirm = ElMessageBox.confirm
  app.config.globalProperties.$prompt = ElMessageBox.prompt
  app.config.globalProperties.$alert = ElMessageBox.alert
  
  app.mount(div)
  document.body.appendChild(div)
}

export function destroy() {
  if (app) {
    app.unmount()
    const div = document.getElementById(this.name)
    if (div) document.body.removeChild(div)
  }
}
